package com.kuhyygy.sqlite.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.kuhyygy.bean.User;

public class SqliteDao {
	
	private DBHelper dbHelper;
	private SQLiteDatabase db;
	
	public SqliteDao(Context context) {
		dbHelper = new DBHelper(context);
		db = dbHelper.getWritableDatabase();
	}
	
	public void add(User u) {
		db.execSQL("insert into t_user (id, name) values (?, ?)", new Object[]{u.getId(), u.getName()});
	}
	
	public Cursor getAllPerson() {
		return db.query("t_person", new String[]{"_id", "name", "gender"}, null, null, null, null, null);
	}
	
	public User findById(int id) {
		Cursor cur = db.rawQuery("select id, name from t_user t where t.id = ?", new String[]{String.valueOf(id)});
		if (cur.moveToNext()) {
			return new User(cur.getInt(cur.getColumnIndex("id")), cur.getString(cur.getColumnIndex("name")));
		}
		return null;
	}
	
	public List<User> getAllUsers() {
		List<User> list = new ArrayList<User>();
		Cursor cur = db.rawQuery("select * from t_user", null);
		while (cur.moveToNext()) {
			list.add(new User(cur.getInt(cur.getColumnIndex("id")), cur.getString(cur.getColumnIndex("name"))));
		}
		return list;
	}
}
